//
//  BookSearchViewController.m
//  TeacherPro
//
//  Created by DCQ on 2017/12/20.
//  Copyright © 2017年 ZNXZ. All rights reserved.
//

#import "BookSearchViewController.h"
#import "BookSearchHotTitleCell.h"
#import "BookSearchHotContentCell.h"
#import "SearchModel.h"
#import "RepositoryListModel.h"
#import "SearchResultsViewController.h"
#import "BookPreviewDetailViewController.h"

NSString * const  BookSearchHotTitleCellIdentifer = @"BookSearchHotTitleCellIdentifer";
NSString * const  BookSearchHotContentCellIdentifier = @"BookSearchHotContentCellIdentifier";

@interface BookSearchViewController ()<UISearchControllerDelegate,UISearchResultsUpdating>
//searchController
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic, strong) SearchsModel * models;
@property (nonatomic,strong) SearchResultsViewController * searchResultVC;
@end

@implementation BookSearchViewController
- (SearchResultsViewController *)searchResultVC{
    if (!_searchResultVC) {
        _searchResultVC = [[SearchResultsViewController alloc]init];
    }
    return _searchResultVC;
}
- (UISearchController *)searchController{
    if (!_searchController) {
        //创建UISearchController
        _searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchResultVC];
        //设置代理
        _searchController.delegate= self;
        _searchController.searchBar.delegate = self;
         [_searchController setSearchResultsUpdater: self.searchResultVC];
        //包着搜索框外层的颜色
        //    self.searchController.searchBar.barTintColor = [UIColor yellowColor];
        
        //提醒字眼
        _searchController.searchBar.placeholder= @"请输入关键字搜索";
        
        //提前在搜索框内加入搜索词
        
        
        //设置UISearchController的显示属性，以下3个属性默认为YES
        
        //搜索时，背景变暗色
        _searchController.dimsBackgroundDuringPresentation = YES;
        
        //搜索时，背景变模糊
        //    self.searchController.obscuresBackgroundDuringPresentation = NO;
        
        //点击搜索的时候,是否隐藏导航栏
        //    self.searchController.hidesNavigationBarDuringPresentation = NO;
        
        if (IOS8) {
            [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"取消"];
        }else{
            
            [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].title = @"取消";
        }
        
    }
    return _searchController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationItemTitle:@"搜索书籍"];
    [self requestListQuerySearchWords];
}
#pragma mark ---
- (void)requestListQuerySearchWords{
     NSMutableDictionary * parameterDic = nil;
    [self sendHeaderRequest:[NetRequestAPIManager getRequestURLStr:NetRequestType_QuerySearchWords] parameterDic:parameterDic requestMethodType:RequestMethodType_POST requestTag:NetRequestType_QuerySearchWords];
    
}
- (void)setNetworkRequestStatusBlocks{
    WEAKSELF
    [self setNetSuccessBlock:^(NetRequest *request, id successInfoObj) {
        STRONGSELF
        if (request.tag == NetRequestType_QuerySearchWords) {
            strongSelf.models = [[SearchsModel alloc]initWithDictionary:successInfoObj error:nil];
             [strongSelf confighHeaderView];
            [strongSelf updateTableView];
        }
    }];
}

- (void)confighHeaderView{
    
    //位置
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.searchResultVC.searchVC = self.searchController;
#warning 如果进入预编辑状态,searchBar消失(UISearchController套到TabBarController可能会出现这个情况),请添加下边这句话
    self.definesPresentationContext=YES;
    WEAKSELF
    self.searchResultVC.selectedBlock = ^(RepositoryModel *model,NSIndexPath * indexPath) {
        [weakSelf gotoDetailVC:model withIndexPath:indexPath];
    };
}

- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BookSearchHotTitleCell class]) bundle:nil] forCellReuseIdentifier:BookSearchHotTitleCellIdentifer];
    [self.tableView registerClass: [BookSearchHotContentCell class] forCellReuseIdentifier:BookSearchHotContentCellIdentifier];
}
#pragma mark ---


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 0;
    if (self.models) {
        row = 2;
    }
    return row;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 0;
    if (indexPath.row == 0) {
        height = 30;
    }else if (indexPath.row == 1){
        
        height = [BookSearchHotContentCell getCellHeight:self.models.items];
    }
    return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.row == 0) {
        BookSearchHotTitleCell * tempCell =  [tableView dequeueReusableCellWithIdentifier:BookSearchHotTitleCellIdentifer];
        tempCell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell = tempCell;
    }else if (indexPath.row == 1){
        
        BookSearchHotContentCell * tempCell =  [tableView dequeueReusableCellWithIdentifier:BookSearchHotContentCellIdentifier];
        [tempCell setupData:self.models.items];
        tempCell.backgroundColor = [UIColor whiteColor];
        WEAKSELF
        tempCell.searchBlock = ^(NSString *searchText) {
            [weakSelf searchHot:searchText];
        };
        tempCell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell = tempCell;
    }
    return cell;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (void)searchHot:(NSString *)searchText{
    
    self.searchController.searchBar.text = searchText;
    [self.searchController.searchBar becomeFirstResponder];
}
#pragma mark ----
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//谓词搜索过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSLog(@"updateSearchResultsForSearchController");
 
}
- (UIRectEdge)getViewRect{
    
    return UIRectEdgeNone;
}
#pragma mark - UISearchBarDelegate

- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//    [self.tabBarController.tabBar setHidden:YES];
    if (searchText.length == 0) {
         [self.searchResultVC cancelSearch];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //这里也可以不做取消操作，而是该用确认搜索的操作，使用.h中的代理把值传到搜索结果那里进行网络请求
//    [self.tabBarController.tabBar setHidden:NO];
    NSLog(@"---------------Cancel");
    [self.searchResultVC cancelSearch];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"---------------%@",searchBar.text);
    [self.searchResultVC searchMyInput:searchBar.text];
}
- (void)gotoDetailVC:(RepositoryModel *)model withIndexPath:(NSIndexPath *)indexPath{
    BOOL existsState = NO;
    if ([model.hasInBookShelf integerValue] == 1) {
        existsState = YES;
    }
    NSString * bookType = model.bookType;
    BookPreviewDetailViewController * detail = [[BookPreviewDetailViewController alloc]initWithBookId:model.id withBookType:bookType withExistsBookcase:existsState];
    detail.indexPath = indexPath;
    detail.selectedBlock = ^(NSIndexPath *indexPath) {
       
        model.hasInBookShelf = @(1);
        [self.searchResultVC updateCellAtIndexPath:indexPath];
    };
    [self pushViewController:detail];
}

@end
